package com.example.service.impl;

import com.example.mapper.DeptLogMapper;
import com.example.mapper.UserMapper;
import com.example.msg.PageBean;
import com.example.msg.Result;
import com.example.pojo.DeptLog;
import com.example.pojo.User;
import com.example.service.DeptLogService;
import com.example.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private DeptLogService deptLogService;


    @Override
    public PageBean list(Integer page, Integer pageSize) {

        Page<Object> result = PageHelper.startPage(page, pageSize);
        List<User> list = userMapper.list();
        return new PageBean(result.getTotal(), list);

    }

    /**
     * Transactional 默认情况下 只有出现RuntimeException 才会回滚
     * 可以指定rollbackFor属性 作用于异常范围
     * propagation 事务传播行为
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result deleteById(Integer id) throws Exception {
        try {
            id = 1;
            userMapper.updateById(id);
            id = 2;
//        System.out.println(1 / 0);
            if (true) {
                throw new ClassNotFoundException("出错了");
            }
            userMapper.updateById(id);
        } finally {
//            放在finally 一定会记录操作日志的
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(new Date());
            deptLog.setDescription("娟娟脸软乎！！！");
            deptLogService.insert(deptLog);
        }

        return Result.success();
    }
}
